package com.luckdraw.util;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.nutz.lang.Strings;
import org.nutz.lang.Xmls;
import org.nutz.lang.util.NutMap;

public class TenpayUtil {
	
	public static SortedMap<String,Object> toSortedMap(NutMap map){
		SortedMap<String,Object> sortedMap = new TreeMap<String, Object>();
		for (String pname : map.keySet()) {
			if ("sign".equals(pname) || Strings.isEmpty(map.getString(pname))) {
				continue;
			}
			sortedMap.put(pname, map.getString(pname));
		}
		return sortedMap;
	}
	
	/**
	 生成签名
	 */
	public static String genPackageSign(SortedMap<String, Object> params,String signKey) {
		StringBuilder sb = new StringBuilder();
		for(String key:params.keySet()){
			if ("sign".equals(key) || Strings.isEmpty(String.valueOf(params.get(key)))) {
				continue;
			}
			sb.append(key).append("=").append(params.get(key)).append("&");
		}
		sb.append("key=");
		sb.append(signKey);
		String packageSign = "";
		try {
			packageSign = SecurityUtil.md5(sb.toString()).toUpperCase();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return packageSign;
	}



	public static boolean checkSign(NutMap params,String apiKey) {
		String sign = null;
		if(params==null||Strings.isBlank((sign=params.getString("sign")))){
			return false;
		}else if(sign.equals(genPackageSign(toSortedMap(params), apiKey))){
			return true;
		}
		return false;
	}
	
	public static String paramsToXml(Map<String, String> params,String key){
		SortedMap<String, Object> map = new TreeMap<String, Object>();
		for (String pname : params.keySet()) {
			if ("sign".equals(pname) || Strings.isEmpty(params.get(pname))) {
				continue;
			}
			map.put(pname, params.get(pname));
		}
		String sign = genPackageSign(map,key);
		map.put("sign", sign);
		String xmlStr = Xmls.mapToXml(NutMap.WRAP(map));
		return xmlStr;
	}
}
